package cs4;

import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;

/*
 * jdk8中日期时间API
 */
public class DateTest1 {
    /*
     * LocalDate,LocalTime,LocalDateTime
     */
    @Test
    public void test(){
        //now():获取当前日期时间
        LocalDate localDate=LocalDate.now();
        LocalTime localTime=LocalTime.now();
        LocalDateTime localDateTime=LocalDateTime.now();
        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);
        //of():设置指定日期时间
        LocalDate localDate1=LocalDate.of(2020, 5, 8);
        System.out.println(localDate1);
        //getXxx():获取相关属性
        System.out.println(localDateTime.getDayOfMonth());
        //withXxx():设置相关属性
        System.out.println(localDate.withDayOfMonth(22));
        //plus/minusXxx
        System.out.println(localDate1.plusDays(5));
    }

    /*
     * Instant
     */
    @Test
    public void test1(){
        //now():获取本初子午线对应的标准时间
        Instant instant=Instant.now();
        System.out.println(instant);

        //添加时间的偏移量
        System.out.println(instant.atOffset(ZoneOffset.ofHours(8)));

        //获取自1970年1月1日0时0分0秒开始的毫秒数
        System.out.println(instant.toEpochMilli());

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例
        Instant instant1=Instant.ofEpochMilli(1234355555555l);
        System.out.println(instant1);
    }
    /*
     * DateTimeFormatter:格式化或解析日期时间
     */
    @Test
    public void test2(){
        //方式一:预定义的标准格式
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        LocalDateTime localDateTime=LocalDateTime.now();
        String str1=formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);
        //解析:字符串-->日期
        TemporalAccessor parse=formatter.parse("2022-09-16T21:47:50.2497226");
        System.out.println(parse);

        //方式二:本地化相关的格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        //格式化
        String str2=formatter1.format(localDateTime);
        System.out.println(str2);
        //解析
        TemporalAccessor parse1=formatter1.parse("2022/9/16 下午9:56");
        System.out.println(parse1);

        //方式三:自定义的格式
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str3 = formatter2.format(localDateTime);
        System.out.println(str3);
        TemporalAccessor parse2=formatter2.parse("2022-09-16 09:59:29");
        System.out.println(parse2);
    }
}
